<?php

namespace addons\kuerp\controller;

use addons\kuerp\model\StaffMember;
use addons\kuerp\model\Admin;
use app\admin\model\department\Admin as AdminDepartment;
use addons\kuerp\model\GoodsSales as GoodsSalesModel;
use addons\kuerp\model\CustomersUser;
use addons\kuerp\model\Accounts;
use addons\kuerp\model\ContractFile;
use addons\kuerp\model\ContractOther;
use addons\kuerp\model\ContractProduct;
use addons\kuerp\model\ExamineRecord;
use addons\kuerp\model\Flows;
use addons\kuerp\model\FormField;
use addons\kuerp\model\OperationLog;
use addons\kuerp\model\Ratio;
use addons\kuerp\model\Receivables;
use addons\kuerp\model\Message;
use addons\kuerp\model\Staff;
use addons\kuerp\model\CustomerProduct;
use addons\kuerp\model\GoodsSalesInfo;
use PhpOffice\PhpWord\TemplateProcessor;
use think\Db;
use think\Exception;

/**
 * 销货单
 */
class GoodsSales extends StaffApi
{
    protected $noNeedLogin = [];
    protected $noNeedRight = [];

    public function _initialize()
    {
        parent::_initialize();
    }

    //创建订单
    public function addContract()
    {
        $params = $this->request->post();

        // var_dump($params);die;
        // 表单验证
        // if (($result = $this->kuerpValidate($params, get_class(), 'create')) !== true) {
        //     $this->error($result);
        // }
        $result = FormField::checkFields(FormField::CONTRACT_TYPE,$params);
        if ($result !== true) {
            $this->error($result);
        }
        Db::startTrans();
        try {
            $result = GoodsSalesModel::createContract($params,['goods_code_caijia'=>$this->goods_code_caijia,'goods_code_xunjia'=>$this->goods_code_xunjia,'goods_code_wls'=>$this->goods_code_wls]);
            $customerModel = new \addons\kuerp\model\Customers();
            // $customerInfo = $customerModel->where(['id' => $params['customer_id']])->find();
            // if (!in_array($customerInfo['follow_status'], ['售后回访', '已经购买'])) {
                $customerModel->where(['id' => $params['customer_id']])->update(['follow_status' => '成交']);
            // }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('添加订单成功');
        }
    }


    //获取select订单列表
    public function getSelectList()
    {
        $limit = input("limit/d", 10);
        $customer_id = input('customer_id');
        $where = [];
        $name = input('name');
        if ($name) {
            $where['num'] = ['like', "%{$name}%"];
        }
        if ($customer_id) {
            $where['customer_id'] = $customer_id;
        }
        $where['sale_user'] = ['in', $this->auth->sale_users];
        $records = GoodsSalesModel::where($where)->with(['staffmember'])->field('id,purchase_code,createtime,real_money,sale_user')->paginate($limit);
        $this->success('请求成功', $records);
    }


    //获取订单编号
    public function getContractNumber()
    {
        $this->success('请求成功', [
            'number' => $this->getCodes('', 11), 
            'goodstypes' => config('site.goods_buy_type'),
            'accounts' => Accounts::where('status', 1)->field('id,account_name')->select(),//结算账户

        ]);
    }
    
    //获取开单默认信息 销售员 仓库
    public function getDefaultInfo()
    {
        $data = [
            'staff' => [
                'id' => $this->auth->staff_member_id ?? 0,
                'name' => $this->auth->nickname,
            ],
            'store' => $this->auth->stores_info ?? [],
            'goodstypes' => config('site.goods_buy_type'),
            'accounts' => Accounts::where('status', 1)->field('id,account_name')->select(),//结算账户
        ];
        $this->success('请求成功', $data);
    }

    //获取订单列表
    public function getList()
    {
        $limit = input("limit/d", 10);
        $customer_id = input('customer_id');

        $name = input('name');
        $is_invoice = input('is_invoice');//1是 2否 是否开发票
        $params = $this->request->post();

        $where= FormField::updateWhereField(FormField::CONTRACT_TYPE,$params);
        $times='';
        if (isset($params['createtime']) && $params['createtime']) {//跟进状态
            $createtime = $params['createtime'];
            $times = setTimes($createtime, 'time');
            $where['goods_sales.purchase_time'] = ['between', $times];
        }
        if ($name) {
            $where['purchase_code|serials|lock_code|goods_sales.note|customers.customer_name'] = ['like', "%{$name}%"];
        }
        if ($is_invoice) {
            // if ($is_invoice == 1) {
            //     $where['invoice_file_ids'] = ['neq', ''];
            // } else {
            //     $where['invoice_file_ids'] = ['eq', ''];
            // }
        }
        $sale_users = $this->auth->sale_users;
        //系统设置特定审核人员
        $config_examine_admins = config('site.examine_admins');
        if (!empty($config_examine_admins[$this->auth->id])) {
            $config_examine_admins = explode(',', $config_examine_admins[$this->auth->id]);
            //获取对应销售id
            $config_sale_users = (new StaffMember())->getStaffMemberIds($config_examine_admins);
            $sale_users = array_merge($sale_users,$config_sale_users);
        }
        if (isset($params['staff_id']) && $params['staff_id']) {//下级员工筛选
            $where['sale_user'] = $params['staff_id'];
        } else {
            if (isset($params['type']) && $params['type']) {//客户分类
                if ($params['type'] == 1) {//我的客户
                    $where['sale_user'] = $this->auth->id;
                } elseif ($params['type'] == 2) {//下属负责的客户
                    
                    //本人存在 则剔除自己
                    if (in_array($this->auth->staff_member_id,$sale_users)) {
                        $sale_users = array_diff($sale_users, [$this->auth->staff_member_id]);
                    }
                    $where['sale_user'] = ['in', $sale_users];
                }else{
                    $where['sale_user'] = ['in', $sale_users];
                }
            } else {
                $where['sale_user'] = ['exp', Db::raw(' in ('.implode(',', $sale_users).')  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];//['in', $this->auth->sale_users];
            }
        }
        //审核状态 3审核中、1审核通过、2审核未通过
        if (isset($params['check_status'])) {
            //0待审核、3审核中、1审核通过、2审核未通过、4撤销
            if ($params['check_status'] == 3) {
                $where['examine_status'] = ['not in', [ '1', '2']];
                // $where['examine_index'] = ['exp', Db::raw('>0 OR (examine_index = 0 && examine_adminids != "")')];
            } elseif ($params['check_status'] == 1) {
                $where['examine_status'] = 1;
            } elseif ($params['check_status'] == 2) {
                $where['examine_status'] = 2;
            } 
            // elseif ($params['check_status'] == 4) {
            //     $where['examine_status'] = 4;
            // } elseif ($params['check_status'] == 9) {
            //     $where['examine_status'] = 9;
            // }
        }
        if ($customer_id) {
            $where['customers_id'] = $customer_id;
        }
        if (isset($params['id_list'])) {//日志 查询id列表
            $where = [];
            $where['id'] = ['in', explode(',', $params['id_list'])];
        }

        $records = GoodsSalesModel::where($where)->with([
            'customers',
            'staffmember',
        ])->order('id desc')->paginate($limit);
        foreach ($records as $row) {
            $row->getRelation('customers')->visible(['customer_name']);
            $row->getRelation('staffmember')->visible(['name', 'admin_id']);
        }
        $records = $records->toArray();
        $data = $records['data'];
        if ($data) {
            $adminIds = array_column(array_column($data, 'staffmember'), 'admin_id');
            $adminIds = array_unique($adminIds);
            $adminList = Admin::where('id', 'in', $adminIds)->field('id,nickname,avatar')->select();
        }
        $contractId = '';
        foreach ($data as $k => $v) {
            $be_money = $v['real_money'] - $v['pay_money'];
            $be_ratio = $v['real_money'] > 0 ? round($v['pay_money'] / $v['real_money'] * 100, 2) : 0;
            $v['receivables'] = [
                'repayment_money' => $v['pay_money'],
                'be_money' => $be_money,
                'ratio' => $be_ratio
            ];
            $v['staffmember']['nickname'] = $adminList[$v['staffmember']['admin_id']]['nickname'] ?? $v['staffmember']['name'];
            $avatar = $adminList[$v['staffmember']['admin_id']]['avatar'] ?? '';
            $avatar = $avatar ? $avatar : '/assets/img/avatar.png';
            $avarar = strpos($avatar, 'http') === false ? request()->domain() . $avatar : $avatar;
            $v['staffmember']['avatar'] = $avarar;
            $v['createtime'] = date('Y-m-d', $v['purchase_time']);
            if ($v['examine_status'] == 0 && ($v['examine_index'] > 0 || ($v['examine_index'] == 0 && $v['examine_adminids'] != ''))) {
                $v['examine_status'] = 3;
            }
            // if (empty($v['receivables'])) {
            //     $v['receivables'] = [
            //         'repayment_money' => 0,
            //         'be_money' => $v['money'],
            //         'ratio' => 0
            //     ];
            // } else {
            //     $be_money = $v['money'] - $v['receivables']['repayment_money'];
            //     $be_ratio = 0;
            //     if($v['money'] > 0){
            //         $be_ratio = round($v['receivables']['repayment_money'] / $v['money'] * 100, 2);
            //     }
            //     $v['receivables'] = [
            //         'repayment_money' => $v['receivables']['repayment_money'],
            //         'be_money' => ($be_money > 0) ? $be_money : 0,
            //         'ratio' => $be_ratio
            //     ];
            // }
            $data[$k] = $v;
            $contractId = $v['id'].','.$contractId;
        }
        $whereT['contract_id']=array('in',$contractId);
        $statics = GoodsSalesModel::where($where)->with(['customers'])->field('sum(real_money) as real_money,sum(back_money) as back_money,sum(pay_money) as pay_money')->find();
        $moneyinfo['back_money'] = $statics['back_money'] ? sprintf("%.2f",$statics['back_money']) : 0;;//返款
        $moneyinfo['repayment_money'] = $statics['pay_money'] ? sprintf("%.2f",$statics['pay_money']) : 0;//已回款
        $moneyinfo['allmoney'] = $statics['real_money'] ? sprintf("%.2f",$statics['real_money']) : 0;//订单总金额
        $moneyinfo['be_money'] = $moneyinfo['allmoney'] - $moneyinfo['repayment_money'];//未回款
        $moneyinfo['be_money'] = sprintf("%.2f",$moneyinfo['be_money']);
        $moneyinfo['allmoney'] += $moneyinfo['back_money'];//订单总金额
        

        $this->success('请求成功', [
            'moneyinfo' => $moneyinfo,
            'total' => $records['total'],
            'per_page' => $records['per_page'],
            'current_page' => $records['current_page'],
            'last_page' => $records['last_page'],
            'data' => $data
        ]);
    }


    //获取客户相关订单列表
    public function getCustomerContacts()
    {
        $limit = input("limit/d", 10);
        $customer_id = input('customer_id');
        $contacts_id = input('contacts_id');
        $where = [];
        if ($customer_id) {
            $where['customers_id'] = $customer_id;
        }
        if ($contacts_id) {
            $where['contacts_id'] = $contacts_id;
        }
        $records = GoodsSalesModel::where($where)
            ->field('id,real_money,purchase_code,examine_status,pay_money,back_money,examine_index,examine_adminids,createtime,serials,lock_code')->order('id desc')->paginate($limit);

        $records = $records->toArray();
        foreach ($records['data'] as $k => $v) {
            $be_money = $v['real_money'] - $v['pay_money'];
            $be_ratio = $v['real_money'] > 0 ? round($v['pay_money'] / $v['real_money'] * 100, 2) : 0;
            $v['receivables'] = [
                'repayment_money' => $v['pay_money'],
                'be_money' => $be_money,
                'ratio' => $be_ratio
            ];
            $v['createtime'] = date('Y-m-d H:i:s', $v['createtime']);
            if ($v['examine_status'] == 0 && ($v['examine_index'] > 0 || ($v['examine_index'] == 0 && $v['examine_adminids'] != ''))) {
                $v['examine_status'] = 3;
            }
            // if (empty($v['receivables'])) {
            //     $v['receivables'] = [
            //         'repayment_money' => 0,
            //         'be_money' => $v['money'],
            //         'ratio' => 0
            //     ];
            // } else {
            //     $be_money = $v['money'] - $v['receivables']['repayment_money'];
            //     $be_ratio = 0;
            //     if($v['money']>0){
            //         $be_ratio = round($v['receivables']['repayment_money'] / $v['money'] * 100, 2);
            //     }
            //     $v['receivables'] = [
            //         'repayment_money' => $v['receivables']['repayment_money'],
            //         'be_money' => ($be_money > 0) ? $be_money : 0,
            //         'ratio' => $be_ratio
            //     ];
            // }
            $records['data'][$k] = $v;
        }
        $this->success('请求成功', $records);
    }


    //获取订单详情
    public function getDetail()
    {
        $id = input('id');
        $contract = GoodsSalesModel::where(['goods_sales.id' => $id])->with([
            'customers',
            'staffmember',
        ])->find();
        if (empty($contract)) {
            $this->error('订单不存在');
        }
        $contract = $contract->toArray();
        $receivablesMoney = $contract['pay_money'];//Receivables::where(['contract_id' => $contract['id'], 'check_status' => 2])->sum('money');
        //回款金额
        $contract['receivables_money'] = $receivablesMoney;
        $contract['is_examine'] = 0;
        $examine_index = 0;
        $cur_flows_item = 0;
        $last_examine_indexs = [];
        if ($contract['examine_status'] == 0){
            //判断当前人是否有审核权限
            //获取审批流程
            $flows = Flows::where(['relation_type' => Flows::GOODSSALE_STATUS, 'status' => 1])->find();
            
            if (!empty($flows)){
                $flows['flow_items'] = json_decode($flows['flow_items'], true);
                //判断流程中是否有当前用户审核
                foreach ($flows['flow_items'] as $key => $value) {
                    if (in_array($this->auth->id, explode(',',$value['admin_id'])) ) {
                        $examine_index = $key + 1;
                        $cur_flows_item = $value;
                        $last_examine_indexs[] = $key;
                        // break;
                    }
                }
            }
            //系统设置特定审核人员
            $config_examine_admins = config('site.examine_admins');
            $config_adminids = [];
            $sale_users = $this->auth->sale_users;
            if (!empty($config_examine_admins[$this->auth->id])) {
                $config_adminids = explode(',', $config_examine_admins[$this->auth->id]);
                //获取对应销售id
                $config_sale_users = (new StaffMember())->getStaffMemberIds($config_adminids);
                $sale_users = array_merge($sale_users,$config_sale_users);
            }
            //当前用户在审核流程中 且 当前用户是销售员的上级
            if ($examine_index > 0 && in_array($contract['sale_user'], $sale_users)) {
                //未到当前用户的审批层级或者已到当前用户的审批层级且当前用户没有还审批
                if ($examine_index > $contract['examine_index'] || ($examine_index == $contract['examine_index'] && $cur_flows_item['stafftype'] == 2 && !in_array($this->auth->id, explode(',', $contract['examine_adminids'])))) {
                    //在当前人审核范围内
                    if (in_array($contract['examine_index'],$last_examine_indexs)) {
                        if ($contract['examine_index'] == 0) {
                            //获取销售员上级
                            $sale_adminid = StaffMember::where(['id' => $contract['sale_user']])->value('admin_id');
                            $parentids = array_unique((new AdminDepartment())->getParentAdminIds($sale_adminid, true, true));
                            //系统设置特定审核人员
                            if (!empty($config_examine_admins)) {
                                $config_parents = [];
                                foreach ($config_examine_admins as $k => $v) {
                                    if (in_array($sale_adminid, explode(',', $v))) {
                                        $config_parents[] = $k;
                                    }
                                }
                                $parentids = array_unique(array_merge($parentids, $config_parents));
                            }
                            // var_dump($this->auth->id, $parentids, in_array($this->auth->id, $parentids));
                            //判断当前人是否直属上级，且是否在审核流程中
                            if (in_array($this->auth->id, $parentids)) {
                                $contract['is_examine'] = 1;
                            }
                        } else {
                            $contract['is_examine'] = 1;
                        }
                    }
                    
                    //当前用户是最后一级时需要前面有审核
                    // if ($examine_index != count($flows['flow_items']) || ($examine_index == count($flows['flow_items']) && $contract['examine_index'] > 0)) {
                    //     $contract['is_examine'] = 1;
                    // }
                }
            }
        }
        if ($contract['examine_status'] == 0 && ($contract['examine_index'] > 0 || ($contract['examine_index'] == 0 && $contract['examine_adminids'] != ''))) {
            $contract['examine_status'] = 3;
        }
        
        $contract['ratios'] = [];//json_decode($contract['ratios'],true);
        if($contract['ratios']){
            foreach ($contract['ratios'] as $k => $v) {
                $v['staff'] = Staff::where(['id' => $v['staff_id']])->field('id,name,img,post')->find()->toArray();
                $v['money'] = round($contract['money'] * ($v['ratio'] / 100),2);
                $contract['ratios'][$k] = $v;
            }
        }
        
        $be_money = $contract['real_money'] - $contract['pay_money'];
        $be_ratio = 0;
        if($contract['real_money']>0){
            $be_ratio = round($contract['pay_money'] / $contract['real_money'] * 100, 2);
        }
        $contract['receivables'] = [
            'repayment_money' => $contract['pay_money'],
            'be_money' => ($be_money > 0) ? $be_money : 0,
            'ratio' => $be_ratio
        ];
        $contract['is_operation'] = 0;

        if ($contract['sale_user'] == $this->auth->staff_member_id) {
            //是否可以操作
            $contract['is_operation'] = 1;
        }
        $contract['order_date'] = date('Y-m-d H:i', $contract['createtime']);
        //获取客户联系人
        $contract['customeruser'] = [];
        if ($contract['customers_users']) {
            $contract['customeruser'] = CustomersUser::where(['sid' => $contract['customers_id']])->where(['id' => ['in', $contract['customers_users']]])->field('id,first_connect_name as name,first_connect_mobile as phone,job as post,qq_wx_email as email')->select();
        }
        //获取商品信息
        $goods=GoodsSalesInfo::where(['purchase_code'=>$contract['purchase_code']])->with(['goods'])->select();
        foreach ($goods as $row) {
            $row->getRelation('goods')->visible(['goods_name', 'goods_image','id']);
        }
        $list = [];
        if ($goods) {
            $unitids = array_unique(array_column($goods, 'goods_unit'));
            $goodsunits = Db::name('kuerp_unit')->where('id','in',$unitids)->column('name','id');
        }
        $default_img = config('site.default_goods_img');
        $caijiagoods = array_merge($this->goods_code_caijia,$this->goods_code_xunjia);
        $hascaijiagoods = false;
        foreach ($goods as $k=>$v) {
            if (in_array($v['goods_code'],$caijiagoods)) {
                $hascaijiagoods = true;
            }
            $list[$k]['id']=$v['id'];
            $list[$k]['number']=$v['number'];
            $list[$k]['goods_id']=$v['goods']['id'];
            $list[$k]['goods_code']=$v['goods_code'];
            $list[$k]['goods_name']=$v['goods']['goods_name'];
            $list[$k]['img']=cdnurl($v['goods']['goods_image'] != '' ? $v['goods']['goods_image'] : $default_img, true);
            $list[$k]['goods_unit']=$goodsunits[$v['goods_unit']];
            $list[$k]['unit_id']=$v['goods_unit'];
            $list[$k]['price']=$v['unit_price'];
            $list[$k]['back_money']=$v['back_money'];
            $list[$k]['serial']='';
            $list[$k]['goods_type']=$v['goods_type'];
            $list[$k]['period']= $v['period'] ? unserialize($v['period']) : '';
            if (!empty($v['period'])) {
                $period = unserialize($v['period']);
                foreach ($period as $k1=>$v1) {
                    $list[$k]['serial'] .= $v1['serial'].'-'.$v1['remark'].',';
                }
                $list[$k]['serial'] = rtrim($list[$k]['serial'], ',');
            }
            $list[$k]['start_date']=$v['start_date'];
            $list[$k]['end_date']=$v['end_date'];
            $list[$k]['date_range']= [];
            if (!empty($v['start_date']) && !empty($v['end_date'])) {
                $list[$k]['date_range']= [$v['start_date'], $v['end_date']];
            }
            
            $list[$k]['year_number']=$v['year_number'];
            $list[$k]['goods_number']=$v['goods_number'];
            $list[$k]['remark']=$v['remark'];
            // $list[$k]['goods_price']=$v['goods_price'];
        }
        $contract['goods'] = $list;
        $contract['purchase_time'] = date('Y-m-d', $contract['purchase_time']);
        //是否需要开启积分申请
        $score_config = \app\common\model\caijiatong\ShoproConfig::getScoreConfig();
        $is_enable_score = $score_config['consume_get_score'] ?? 0;
        //判断是否需要申请积分
        $contract['enable_apply_score'] = $is_enable_score && $contract['real_money'] == $contract['pay_money'] && $hascaijiagoods ? 1 : 0;

        //标记通知已读
        Message::setRead(['in', [Message::CONTRACT_TYPE, Message::GOODSSALES_TYPE]], $id, $this->auth->id);

        $this->success('请求成功', $contract);
    }

    //获取修改后的订单详情
    public function getContractDetail()
    {
        $id = input('id');
        $contract = GoodsSalesModel::where(['id' => $id])->with([
            'customer', 'contacts', 'ownerStaff', 'orderStaff', 'product', 'receivables'
        ])->find();
        if (empty($contract)) {
            $this->error('订单不存在');
        }
        $contract = $contract->toArray();
        $contract = ContractOther::getOther($contract);
        $receivablesMoney = Receivables::where(['contract_id' => $contract['id'], 'check_status' => 2])->sum('money');
        //回款金额
        $contract['receivables_money'] = $receivablesMoney;
        if ($contract['check_status'] == 0 || $contract['check_status'] == 1) {
            $contract['is_examine'] = ExamineRecord::isExaminse(ExamineRecord::CONTRACT_TYPE, $id);
            $examine = ExamineRecord::where([
                'relation_type' => ExamineRecord::CONTRACT_TYPE,
                'relation_id' => $id,
                'status' => 0,
            ])->find();;
            $contract['examine'] = json_decode($examine['edit_field']);
        } else {
            $contract['is_examine'] = 0;
        }
        if (empty($contract['receivables'])) {
            $contract['receivables'] = [
                'repayment_money' => 0,
                'be_money' => $contract['money'],
                'ratio' => 0
            ];
        } else {
            $be_money = $contract['money'] - $contract['receivables']['repayment_money'];
            $be_ratio = 0;
            if($contract['money'] > 0){
                $be_ratio = round($contract['receivables']['repayment_money'] / $contract['money'] * 100, 2);
            }
            $contract['receivables'] = [
                'repayment_money' => $contract['receivables']['repayment_money'],
                'be_money' => ($be_money > 0) ? $be_money : 0,
                'ratio' => $be_ratio
            ];
        }
        $contract['is_operation'] = 0;

        if ($contract['owner_staff_id'] == $this->auth->id) {
            //是否可以操作
            $contract['is_operation'] = 1;
        }

        //标记通知已读
        Message::setRead(Message::CONTRACT_TYPE, $id, $this->auth->id);

        $customerProducts = CustomerProduct::where(['contract_id' => $contract['id']])->with(['product'])->select();
        $contract['customer_product'] = $customerProducts;

        $this->success('请求成功', $contract);
    }

    //修改订单
    public function editReviewedContract()
    {
        $id = input('id');
        $params = $this->request->post();

        $row = GoodsSalesModel::where(['id' => $id, 'check_status' => 2])->find();
        if (empty($row)) {
            $this->error('订单信息不存在');
        }
        // 表单验证
        if (($result = $this->kuerpValidate($params, get_class(), 'create')) !== true) {
            $this->error($result);
        }
        Db::startTrans();
        try {
            $result = GoodsSalesModel::updateReviewedContract($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('提交修改信息成功');
    }


    //获取附件列表
    public function getFilesList()
    {
        $id = input('contract_id');

        $files = ContractFile::where(['contract_id' => $id])->field('file_id')->with(['file'])->select();
        $this->success('请求成功', $files);
    }

    //添加附件
    public function addFiles()
    {
        $contract_id = input('contract_id');
        $files = input('files');

        $files = ContractFile::addFiles($files, $contract_id);
        if($files){
            $this->success('添加成功');
        }
        $this->error('添加失败');
    }

    //删除附件
    public function deleteFiles()
    {
        $id = input('id');

        $files = ContractFile::where(['file_id' => $id])->delete();
        if($files){
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }

    //撤回审核
    public function cancel()
    {
        $id = input('id');
        $contract = GoodsSalesModel::where(['id' => $id, 'check_status' => ['in', [0, 1]]])->find();
        if (empty($contract)) {
            $this->error('订单信息不存在');
        }
        if($contract['owner_staff_id'] != $this->auth->id){
            $this->error('只有订单负责人可以撤回审核');
        }
        $record = ExamineRecord::where([
            'relation_type' => ExamineRecord::CONTRACT_TYPE,
            'relation_id' => $id,
            'status' => 0
        ])->find();
        Db::startTrans();
        try {
            if ($message = Message::where([
                'relation_type' => 'examine',
                'relation_id' => $record['id'],
                'from_staff_id' => $this->auth->id
            ])->find()) {
                Message::where(['id' => $message['id']])->update(['status' => 1, 'read_time' => time()]);
            }
            GoodsSalesModel::where(['id' => $id])->update(['check_status' => 4, 'flow_staff_ids' => '']);
            ExamineRecord::where([
                'relation_type' => ExamineRecord::CONTRACT_TYPE,
                'relation_id' => $id,
                'status' => 0
            ])->update(['status' => 3]);

            OperationLog::createLog(OperationLog::CONTRACT_TYPE, $id, '撤回审批');
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();;
            $this->error($e->getMessage());
        }


        $this->success('撤回成功');
    }

    //修改订单
    public function editContract()
    {
        $id = input('id');
        $params = $this->request->post();
        $row = GoodsSalesModel::where(['id' => $id])->find();
        if (empty($row)) {
            $this->error('订单信息不存在');
        }
        // 表单验证
        // if (($result = $this->kuerpValidate($params, get_class(), 'create')) !== true) {
        //     $this->error($result);
        // }
        $result = FormField::checkFields(FormField::CONTRACT_TYPE,$params,$id);
        if ($result !== true) {
            $this->error($result);
        }
        Db::startTrans();
        try {
            $result = GoodsSalesModel::updateContract($params,['goods_code_caijia'=>$this->goods_code_caijia,'goods_code_xunjia'=>$this->goods_code_xunjia,'goods_code_wls'=>$this->goods_code_wls]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('修改订单信息成功');
    }

    //修改订单乙方信息
    public function editContractPartyB()
    {
        $id = input('id');
        $params = $this->request->post();
        $row = GoodsSalesModel::where(['id' => $id])->find();
        if (empty($row)) {
            $this->error('订单信息不存在');
        }

        Db::startTrans();
        try {
            $result = GoodsSalesModel::updateContractPartyB($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('修改订单信息成功');
    }

    //修改订单地址
    public function editContractAddress()
    {
        $id = input('id');
        $params = $this->request->post();
        $row = GoodsSalesModel::where(['id' => $id])->find();
        if (empty($row)) {
            $this->error('订单信息不存在');
        }

        Db::startTrans();
        try {
            $result = GoodsSalesModel::updateContractAddress($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('修改订单信息成功');
    }

    //下载订单
    public function downloadContract()
    {
        $id = input('id');
        $type = input('type', 'word');
        $contract = GoodsSalesModel::where(['id' => $id])
            ->with(['customer', 'contacts', 'orderStaff'])->find();
        if (empty($contract)) {
            $this->error('不能为空');
        }

        $contract = $contract->toArray();

        $contractProduct = ContractProduct::where(['contract_id' => $id])->with(['product'])->select();

        $tmp = new TemplateProcessor('assets/addons/kuerp/phpword/contract.docx');
        \PhpOffice\PhpWord\Settings::setCompatibility(true);
        \PhpOffice\PhpWord\Settings::setOutputEscapingEnabled(true);


        $tmp->setValue('number', $contract['num']);//订单编号
        $tmp->setValue('name', $contract['customer']['name']);//乙方
        $tmp->setValue('signing_time', date('Y年m月d日', strtotime($contract['order_date'])));//签订时间
        $tmp->setValue('signed_at', $contract['signed_at']);//签订地点

        $rows = count($contractProduct);//总行数
        $tmp->cloneRow('one', $rows);//复制行

        for ($i = 0; $i < $rows; $i++) {
            $tmp->setValue("one#" . ($i + 1), $contractProduct[$i]['name'] ?? '');//名称
            $tmp->setValue("two#" . ($i + 1), $contractProduct[$i]['num'] ?? '');//型号
            $tmp->setValue("three#" . ($i + 1), $contractProduct[$i]['number'] ?? '');//数量
            $tmp->setValue("four#" . ($i + 1),
                $contractProduct[$i]['price'] * $contractProduct[$i]['number']);//总价格
        }


        $tmp->setValue("address", $contract['customer']['address']);//金额
        $tmp->setValue("discount_rate", $contract['discount_rate']);//金额
        $tmp->setValue("price", $contract['money']);//金额
        $tmp->setValue("price_big", convertAmountToCn($contract['money']));//汉字金额
        $tmp->setValue("remarks", $contract['remarks']);//备注
        $tmp->setValue("payment", $contract['payment_text'] . $contract['tax_text']);//支付方式
        $tmp->setValue("be_overdue", $contract['be_overdue']);//到期条款
        $tmp->setValue("delivery_time", $contract['delivery_time']);//
        $tmp->setValue("account", $contract['collection_account']);//
        $tmp->setValue("account_name", $contract['collection_name']);//
        $tmp->setValue("bank_name", $contract['collection_deposit']);//
        $tmp->setValue("effective", $contract['effective']);//
        $tmp->setValue("guarantee", $contract['guarantee']);//
//        $tmp->setValue("address", $contract['customer']['address']);//
        $tmp->setValue("legal", $contract['legal']);//
        $tmp->setValue("entrust", $contract['entrust']);//
        $tmp->setValue("handler", $contract['handler']);//
        $tmp->setValue("mobile", $contract['mobile']);//
        $tmp->setValue("fax", $contract['fax']);//
        $tmp->setValue("deposit", $contract['deposit']);//
        $tmp->setValue("y_account", $contract['account']);//
        $tmp->setValue("order_name", $contract['order_staff']['name']);//
        $tmp->setValue("order_mobile", $contract['order_staff']['mobile']);//
        //end 配置

        $filename = $contract['customer']['name'] . $contract['num'] .'-'.date('His'). '.docx';
        $fileurl = './uploads/' . date('Ymd') . '/';
        if (!file_exists($fileurl)) {
            mkdir($fileurl);
        }

        $tmp->saveAs($fileurl . $filename);//另存为


        $model = new \addons\kuerp\model\File();
        $data = [
            'types' => 'file',
            'name' => $filename,
            'save_name' => $fileurl . $filename,
            'size' => filesize($fileurl . $filename),
            'file_path' => trim($fileurl, '.') . $filename,
        ];

        $model->save($data);
        $lastid = $model->getLastInsID();


        $file = cdnurl($model::getUrl($lastid), true);
        if ($type == 'pdf') {
            $docfile = $_SERVER['DOCUMENT_ROOT'] . trim($data['save_name'], '.'); // word文件
            $pdfdir = $_SERVER['DOCUMENT_ROOT'] . trim($fileurl, '.'); // pdf文件
            $cmd = "export HOME=/tmp && libreoffice --headless -convert-to pdf {$docfile} -outdir {$pdfdir}";
            @exec($cmd);
            $pathinfo = pathinfo($file);
            $file = $pathinfo['dirname'] . '/' . $pathinfo['filename'] . '.pdf';
            $filename = $pathinfo['filename'] . '.pdf';
        }

        OperationLog::createLog(OperationLog::CONTRACT_TYPE, $id, '下载订单');
        $this->success('请求成功', ['file' => $file, 'id' => $lastid, 'filename' => $filename]);
    }


    //获取账户列表
    public function getAccountList()
    {
        $accounts = Account::where(['status'=>1])->select();
        $this->success('请求成功', $accounts);
    }

    //订单生效
    public function startContract()
    {
        $id = input('contract_id');
        $row = GoodsSalesModel::get($id);
        if (empty($row)) {
            $this->error('订单信息不存在');
        }

        $model = new GoodsSalesModel();
        $contract = $model->get($id);
        $files = $model->where(['id' => $id])->update(['is_start' => 1]);

        $product = ContractProduct::where(['contract_id' => $row['id']])->select();
        $customerInfo = \addons\kuerp\model\Customer::get($row['customer_id']);
        
        OperationLog::createLog(OperationLog::CONTRACT_TYPE, $id, '客户已确认');
        $this->success('操作成功', $files);
    }

    //终止订单
    public function revokeContract()
    {
        $id = input('contract_id');
        $model = new GoodsSalesModel();
        $row = $model->get($id);
        if (empty($row)) {
            $this->error('信息不存在');
        }
        if($row['owner_staff_id'] != $this->auth->id){
            $this->error('只有订单负责人可以终止订单');
        }
        $files = $model->where(['id' => $id])->update(['contract_status' => 2, 'check_status' => 9]);
        Message::addMessage(Message::CONTRACT_TYPE, $id, $row['owner_staff_id'], $this->auth->id, "订单《{$row['num']}》被终止，请您及时查看！");

        OperationLog::createLog(OperationLog::CONTRACT_TYPE, $id, '终止订单');
        $this->success('操作成功', $files);
    }

    //回执订单
    public function receiptContract()
    {
        $params = $this->request->post();
        if (empty($params['id'])) {
            $this->error('id不能为空');
        }
        if (empty($params['receipt_file_ids'])) {
            $this->error('回执单不能为空');
        }
        if (empty($params['receipt_date'])) {
            $this->error('回执时间不能为空');
        }

        Db::startTrans();
        try {
            $result = GoodsSalesModel::receiptContract($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('回执成功');
    }

    //发票物流
    public function invoiceContract()
    {
        $params = $this->request->post();
        if (empty($params['id'])) {
            $this->error('id不能为空');
        }
        if (empty($params['invoice_file_ids'])) {
            $this->error('发票附件不能为空');
        }
        if (empty($params['invoice_date'])) {
            $this->error('时间不能为空');
        }
        if (empty($params['invoice_logistics_number'])) {
            $this->error('单号不能为空');
        }

        Db::startTrans();
        try {
            $result = GoodsSalesModel::invoiceContract($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('回执成功');
    }


    //获取支付类型文字
    public function getPayTypeText()
    {
        $money = input('money');
        $type = input('type');
        if ($type == '五五') {
            $money = $money / 2;
            $cnMoney = convertAmountToCn($money);
            $content = "订单生效后，发货前，乙方须在当天内预付订单总价定金50%￥{$money}（人民币大写：{$cnMoney}），安装调试合格后，乙方须在当天内付清订单总价尾款50%￥{$money}（人民币大写：{$cnMoney}）";
        } elseif ($type == '三六一') {
            $money1 = ($money / 10) * 3;
            $cnMoney1 = convertAmountToCn($money1);
            $money2 = ($money / 10) * 6;
            $cnMoney2 = convertAmountToCn($money2);
            $money3 = ($money / 10) * 1;
            $cnMoney3 = convertAmountToCn($money3);
            $content = "订单生效后，乙方须在当天内预付订单总价定金30%￥{$money1}（人民币大写：{$cnMoney1}），发货前，乙方须在当天内预付订单总价货款60%￥{$money2}（人民币大写：{$cnMoney2}），设备安装调试后，乙方须在当天内付清订单总价尾款10%￥{$money3}（人民币大写：{$cnMoney3}）。";
        } elseif ($type == '三七') {
            $money1 = ($money / 10) * 3;
            $cnMoney1 = convertAmountToCn($money1);
            $money2 = ($money / 10) * 7;
            $cnMoney2 = convertAmountToCn($money2);
            $content = "订单生效后，发货前，乙方须在当天内预付订单总价定金30%￥{$money1}（人民币大写：{$cnMoney1}），安装调试合格后，乙方须在当天内付清订单总价尾款70%￥{$money2}（人民币大写：{$cnMoney2}）。";
        } else {
            $content = '';
        }

        $this->success('请求成功', $content);
    }


    /**
     * 获取业绩分割比例
     */
    public function getRatio()
    {
        // $ratios = Ratio::where(['status' => 1])->field('name,ratio')->select();
        $ratios = [];//collection($ratios)->toArray();
        foreach ($ratios as $k => $v) {
            $v['ratio'] = json_decode($v['ratio'], true);
            $ratios[$k] = $v;
        }
        $this->success('请求成功', $ratios);
    }
    /**
     * 获取销售单产品
     */
    public function getContractProduct(){
        $contract_id=input('contract_id','','intval');
        if(empty($contract_id)){
            $this->error('参数不能为空');
        }
        $products=ContractProduct::where(['contract_id'=>$contract_id])->with(['product'])->select();

        $this->success('请求成功',$products);
    }

    public function getCustomerGoods()
    {
        $limit=input('limit',10,'intval');
        $customer_id=input('customer_id','','intval');
        if(empty($customer_id)){
            $this->error('参数不能为空');
        }
        $goods=GoodsSalesInfo::where(['customers_id'=>$customer_id])->with(['goods'])->order('id desc')->paginate($limit);
        foreach ($goods as $row) {
            $row->getRelation('goods')->visible(['goods_name', 'goods_image']);
        }
        $goods = $goods->toArray();
        $list = [];
        if ($goods['data']) {
            $unitids = array_unique(array_column($goods['data'], 'goods_unit'));
            $goodsunits = Db::name('kuerp_unit')->where('id','in',$unitids)->column('name','id');
        }
        $default_img = cdnurl(config('site.default_goods_img'), true);
        foreach ($goods['data'] as $k=>$v) {
            $list[$k]['id']=$v['id'];
            $list[$k]['goods_code']=$v['goods_code'];
            $list[$k]['goods_name']=$v['goods']['goods_name'];
            $list[$k]['goods_image']=$v['goods']['goods_image'] ? cdnurl($v['goods']['goods_image'], true) : $default_img;
            $list[$k]['goods_unit']=$goodsunits[$v['goods_unit']] ?? '';
            $list[$k]['serial']='';
            if (!empty($v['period'])) {
                $period = unserialize($v['period']);
                foreach ($period as $k1=>$v1) {
                    $list[$k]['serial'] .= $v1['serial'].'-'.$v1['remark'].',';
                }
                $list[$k]['serial'] = rtrim($list[$k]['serial'], ',');
            }
            // $list[$k]['goods_price']=$v['goods_price'];
        }
        $goods['data']=$list;

        $this->success('请求成功',$goods);
    }

    public function getOrderGoods()
    {
        $limit=input('limit',10,'intval');
        $name  = input('name');
        $customer_id  = input('customer_id');
        $params = $this->request->post();
		$where = [];
		if ($name) {
			$where['goods_name'] = ['like', "%{$name}%"];
		}
		if ($customer_id) {
			$where['goods_sales_info.customers_id'] = $customer_id;
		}
        if (isset($params['createtime']) && $params['createtime']) {//跟进状态
            $createtime = $params['createtime'];
            $times = setTimes($createtime, 'time');
            $where['goods_sales_info.purchase_time'] = ['between', $times];
        }
        //审核状态 3审核中、1审核通过、2审核未通过
        if (isset($params['check_status'])) {
            //0待审核、3审核中、1审核通过、2审核未通过、4撤销
            if ($params['check_status'] == 3) {
                $where['goodssales.examine_status'] = ['not in', [ '1', '2']];
                // $where['examine_index'] = ['exp', Db::raw('>0 OR (examine_index = 0 && examine_adminids != "")')];
            } elseif ($params['check_status'] == 1) {
                $where['goodssales.examine_status'] = 1;
            } elseif ($params['check_status'] == 2) {
                $where['goodssales.examine_status'] = 2;
            } 
        }

        if (isset($params['staff_id']) && $params['staff_id']) {//下级员工筛选
            $where['goods_sales_info.sale_user'] = $params['staff_id'];
        } else {
            if (isset($params['type']) && $params['type']) {//客户分类
                if ($params['type'] == 1) {//我的客户
                    $where['goods_sales_info.sale_user'] = $this->auth->id;
                } elseif ($params['type'] == 2) {//下属负责的客户
                    $sale_users = $this->auth->sale_users;
                    //本人存在 则剔除自己
                    if (in_array($this->auth->staff_member_id,$sale_users)) {
                        $sale_users = array_diff($sale_users, [$this->auth->staff_member_id]);
                    }
                    $where['goods_sales_info.sale_user'] = ['in', $sale_users];
                }else{
                    $where['goods_sales_info.sale_user'] = ['in', $this->auth->sale_users];
                }
            } else {
                $where['goods_sales_info.sale_user'] = ['exp', Db::raw(' in ('.implode(',', $this->auth->sale_users).')  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];//['in', $this->auth->sale_users];
            }
        }

        $goods=GoodsSalesInfo::where($where)->with(['goodssales','goods', 'customers','staff_member'])->order('id desc')->paginate($limit);
        foreach ($goods as $row) {
            $row->getRelation('goods')->visible(['goods_name', 'goods_image']);
            $row->getRelation('customers')->visible(['customer_name']);
            $row->getRelation('staff_member')->visible(['id', 'name', 'admin_id']);
        }
        $goods = $goods->toArray();
        $list = $adminlist = $orderList = [];
        if ($goods['data']) {
            // $customerids = array_unique(array_column($goods['data'], 'customers_id'));
            // $customers = Db::name('kuerp_customers')->where('id','in',$customerids)->column('customer_name','id');
            $unitids = array_unique(array_column($goods['data'], 'goods_unit'));
            $goodsunits = Db::name('kuerp_unit')->where('id','in',$unitids)->column('name','id');
            $adminids = array_unique(array_column(array_column($goods['data'], 'staff_member'), 'admin_id'));
            $adminlist = Db::name('admin')->where('id','in',$adminids)->column('nickname,avatar','id');
            $ordercodes = array_unique(array_column($goods['data'], 'purchase_code'));
            $orderList = Db::name('kuerp_goods_sales')->where('purchase_code','in',$ordercodes)->column('id','purchase_code');
        }
        $default_img = cdnurl(config('site.default_goods_img'), true);
        foreach ($goods['data'] as $k=>$v) {
            $list[$k]['id']=$v['id'];
            $list[$k]['customers_id']=$v['customers_id'];
            $list[$k]['purchase_code']=$v['purchase_code'];
            $list[$k]['goods_code']=$v['goods_code'];
            $list[$k]['goods_name']=$v['goods']['goods_name'];
            $list[$k]['goods_image']=$v['goods']['goods_image'] ? cdnurl($v['goods']['goods_image'], true) : $default_img;
            $list[$k]['goods_unit']=$goodsunits[$v['goods_unit']];
            $list[$k]['customer_name']=$v['customers']['customer_name'];//$customers[$v['customers_id']]['customer_name'];
            $list[$k]['price']=$v['unit_price'];
            $list[$k]['back_money']=$v['back_money'];
            $list[$k]['goods_type']=$v['goods_type'];
            $list[$k]['number']=$v['number'];
            $list[$k]['sale_user']=$v['sale_user'];
            $list[$k]['serial'] = '';
            if (!empty($v['period'])) {
                $period = unserialize($v['period']);
                foreach ($period as $k1=>$v1) {
                    $list[$k]['serial'] .= $v1['serial'].'-'.$v1['remark'].',';
                }
                $list[$k]['serial'] = rtrim($list[$k]['serial'], ',');
            }
            // $list[$k]['goods_price']=$v['goods_price'];
            $avatar = $adminlist[$v['staff_member']['admin_id']]['avatar'] ?? '';
            $list[$k]['staff_member'] = $v['staff_member'];
            $list[$k]['staff_member']['avatar'] = cdnurl($avatar ? : '/assets/img/avatar.png', true);
            $list[$k]['order_id'] = $orderList[$v['purchase_code']];

        }
        $goods['data']=$list;

        $this->success('请求成功',$goods);
    }
}
